import global from '../../core/global.js';
import { Model } from '../model.js';
import { Tiles } from '../tiles.js';
import { Label3D } from '../label.js';
import { Pipeline } from '../pipeline.js';
import { Animation } from '../track-animation.js';
import { Billboard } from '../billboard.js';
import { cameraFlyToRectangle } from '../../core/scene.js';
import { jsonToVec3, calculateBoundingBox, expandBoundingBox } from '../../core/common.js';

export function setBaseURL(url, isDesk) {
	window.isDesk = isDesk;
	window.baseURL = url;
	window.pickId = null;
	window.HighLightLayer = null;
}

// 控制图层显隐
export function showLayerByLayer(opt, showKey) {
	let Layer = global.layerList.get(opt.id);
	if (Layer) {
		if (showKey == 'delete') {
			if (opt.dataType == 'model') {
				Model.remove(opt);
			} else if (opt.dataType == 'tiles') {
				Tiles.remove(opt);
			} else if (opt.dataType == 'Billboard') {
				Billboard.remove(opt.id);
				global.layerList.remove(opt.id);
			} else if (opt.dataType == 'animation') {
				let animEntity = Layer.animation.animEntity();
				animEntity.enabled = !animEntity.enabled;
				Layer.animation.paused = !Layer.animation.paused;
			}
			if (opt.dataType != 'animation') global.layerList.remove(opt.id);
		} else Layer[showKey] = !Layer[showKey];
		return false;
	} else {
		return true;
	}
}

// 控制图层定位
export function flyToLayer(opt, cb) {
	let Layer = global.layerList.get(opt.id);
	if (Layer && Layer.extent) {
		let cameraController = GlobalViewer.scene.mainCamera.cameraController();
		cameraController.flyToRectangle(Layer.extent(), 2, 0, -80, 0);
	} else if (opt.dataType == 'animation') {
		Animation.flyTo(opt, cb);
	} else if (opt.dataType == 'model') {
		Model.flyTo(opt, cb);
	} else if (opt.dataType == 'tiles') {
		Tiles.flyTo(opt);
	} else {
		console.log('缺少起飞条件！！！');
	}
}

// 清除新增和编辑时候的预览图层
export function cleanTestLayer() {
	let instance = global.testLayer;
	if (instance) {
		if (instance.id) {
			Billboard.remove(instance.id);
			Label3D.remove(instance.id);
			Pipeline.remove(instance.id);
			Animation.remove(instance.id);
			Model.remove({ id: instance.id });
			Tiles.remove({ id: instance.id });
			global.testLayer = null;
		} else {
			if (instance.type == 'ImageryLayer') {
				try {
					//web端使用removeImageryLayer移除底图会报错，但效果已生效
					window.viewer.scene.globe.removeImageryLayer(instance);
					instance.delete();
				} catch (error) {}
			}
			if (instance.isTerrain) window.viewer.scene.globe.setDefaultTerrain();
			else {
				instance.delete();
			}
			delete global.testLayer;
			global.testLayer = null;
		}
	}
}

// 退出清空所有图层效果
export function cleanAllLayer() {
	let layerIdList = global.layerList.getAllKey();
	layerIdList.forEach((layerId) => {
		deleteLayer(layerId);
	});
}

// 删除地图图层
export function deleteLayer(id) {
	// 确保 Layer 存在
	let Layer = global.layerList.get(id);
	if (!Layer) {
		return; // 如果图层不存在，提前退出
	}
	Billboard.remove(instance.id);
	Label3D.remove(id);
	Pipeline.remove(id);
	Animation.remove(id);
	Tiles.remove({ id: id });
	Model.remove({ id: id });
	// 处理 terrainProvider 类型的图层
	if (Layer.isTerrain) {
		window.viewer.scene.globe.setDefaultTerrain();
	}
	// 删除 Imagery Layer
	if (Layer.type == 'ImageryLayer') {
		try {
			window.viewer.scene.globe.removeImageryLayer(Layer);
		} catch (error) {
			// console.error(`Error removing imagery layer with id ${id}:`, error);
		}
	}
	// 从 global.layerList 删除图层
	if (global.layerList.get(id)) {
		if (window.isDesk) {
			global.layerList.remove(id);
		} else {
			setTimeout(() => {
				global.layerList.remove(id);
			}, 10);
		}
	}
}

// 鼠标点击实体的特征返回整个layer
export function chooseLayer(e, cb) {
	let scene = GlobalViewer.scene;
	let feature = scene.getFeatureByMouse();
	function findLayerTag(feature) {
		if (!feature) return null; // 如果没有feature，返回null
		if (feature.tag) return feature.tag; // 如果当前feature有tag，返回它的值
		return findLayerTag(feature.parent); // 递归查找父级
	}
	let layer =
		SSmap.GeoJsonLabelLayer.getSelect(feature) || SSmap.GeoJsonPolylineLayer.getSelect(feature) || SSmap.GeoJsonPolygonLayer.getSelect(feature);
	let backInfo = {};
	if (layer) {
		let id = feature.getProperty('id');
		this.cleanHighLight();
		window.pickId = typeof id === 'number' ? id : Number(id);
		window.HighLightLayer = layer;
		window.HighLightLayer && window.HighLightLayer.setHighLight && window.HighLightLayer.setHighLight(window.pickId, Boolean(window.HighLightLayer)); //设置面高亮
		let keys = layer.getKeys();
		let size = keys.size();
		backInfo.properties = [];
		for (let i = 0; i < size; i++) {
			let key = keys.get(i);
			backInfo.properties.push({
				key: key,
				value: layer.getPropertie(id, key),
			});
		}
	}
	backInfo.layerId = findLayerTag(feature);
	cb && cb(backInfo);
}

export function cleanHighLight() {
	if (window.HighLightLayer && window.HighLightLayer.setHighLight && window.pickId) {
		//隐藏上一个选中的id面
		window.HighLightLayer.setHighLight(window.pickId, false); //设置面高亮
		window.HighLightLayer = null;
		window.pickId = null;
	}
}

// 获取已加载图层内 某type id
export function getLayerIdByType(type, cb) {
	let LayerIdList = [];
	let getType = '';
	let layerObj = global.layerList.getAll();
	// 如果没有传递type参数，则默认为ImageryLayer
	if (typeof type === 'function') {
		cb = type;
		getType = 'ImageryLayer';
	} else getType = type;
	for (let key in layerObj) {
		if (layerObj[key].type == getType) LayerIdList.push(key);
	}
	cb && cb(LayerIdList);
	return LayerIdList;
}

// 获取已加载图层内 某type 图层列表
export function getLayerByType(type) {
	let LayerList = [];
	let layerObj = global.layerList.getAll();
	for (let key in layerObj) {
		if (layerObj[key].type == type) LayerList.push(layerObj[key]);
	}
	return LayerList;
}
